## -*- coding: UTF-8 -*-
import os.path
import gtk

from ... import collection as c
from ... import log
from ... import html
from ... import core
from ... import path
from ... import strunicode as su
from ... import exceptions

def initialize():
    """
    Initialize the module
    """
    
def render_shelf_page(link_text, generated_files_dir, arguments):
    """
    Render shef page
    """
    if link_text=="":
        return render_shelves_page(link_text, generated_files_dir, arguments)
    
    # process arguments
    if "action" in arguments:
        if arguments['action'] == "delete":
            # ask confirmation
            ret = core.confirmation(_(u"Do you really want to delete book shelf “%s”?") % link_text)
            
            if ret == gtk.RESPONSE_YES:
                # delete
                c.delete_book_shelf(link_text, commit=True)
                return _(u"Book shelf “%s” successfully deleted.") % link_text, [], None
            
        elif arguments['action'] == "edit":
            # display book shelf description edit dialog
            xml = gtk.glade.XML(path.get_data_path("pybookshelf.glade"), root="book_shelf_edit_dialog",
                domain="pybookshelf")
            
            dialog = xml.get_widget("book_shelf_edit_dialog")
            shelf_name = link_text
            dialog.set_title(_("Edit book shelf"))
            shelf_description_text = xml.get_widget("shelf_description_text")
            buf = shelf_description_text.get_buffer()
            shelf_description = c.get_book_shelf_description(shelf_name)
            if shelf_description is None:
                shelf_description = ""
            buf.set_text(shelf_description)
            xml.get_widget("shelf_name_entry").set_text(shelf_name)
            
            while True:
                response = dialog.run()
                dialog.hide()
                shelf_description = buf.get_text(buf.get_start_iter(), buf.get_end_iter())
                shelf_description = su.ustr2unicode(shelf_description)
                shelf_new_name = su.ustr2unicode(xml.get_widget("shelf_name_entry").get_text())
                
                if response != 1:
                    break
                
                if shelf_new_name == "":
                    core.error(_("Book shelf name field may not be empty"))
                    xml.get_widget("shelf_name_entry").grab_focus()
                    continue

                c.set_book_shelf_description(link_text, shelf_description)
                
                if shelf_new_name != shelf_name:
                    try:
                        c.rename_book_shelf(link_text, shelf_new_name)
                        shelf_name = shelf_new_name
                    except exceptions.CollectionError, e:
                        core.error(_("Unable to edit book shelf: %s") % e.message)
                        xml.get_widget("shelf_name_entry").grab_focus()
                        continue
                
                break
                    
            dialog.destroy()
            
            # go to corresponding page
            return "shelf://%s" % shelf_name
            
    shelf_template = html.get_html_template("shelf")
    book_template = html.get_html_template("shelf_book")
    author_template = html.get_html_template("shelf_book_author")
    
    title = _(u"Shelf: “%s”") % link_text
    books = ""
        
    # find books list for this shelf
    for file_id in c.get_book_shelf_books(link_text):
        book_title = c.get_book_title(file_id)
        authors = list()
        
        for a in c.get_book_authors(file_id):
            authors.append(author_template % {
                'author_name_enc': html.quote(a),
                'author_name': a
                })
        
        book = book_template % {
            'book_title': book_title,
            'file_id': file_id,
            'authors': ", ".join(authors)
            }
        books += book
        
    if books == "":
        books = _("<i>No books found.</i>")
    
    shelf_description = c.get_book_shelf_description(link_text)
    if shelf_description is None:
        shelf_description = ""
        
    body = shelf_template % {
        'shelf_title': title,
        'edit_tooltip': _("Edit book shelf"),
        'delete_tooltip': _("Delete book shelf"),
        'shelf_name_enc': html.quote(link_text),
        'icon_edit': html.stock_img_url("edit.png"),
        'icon_delete': html.stock_img_url("delete.png"),
        'shelf_description': shelf_description,
        'books': books
        }
    return body, [], title

def render_shelves_page(link_text, generated_files_dir, arguments):
    
    shelves_template = html.get_html_template("shelves")
    shelf_template = html.get_html_template("shelves_shelf")
    
    shelves = list()
    for shelf, descriptions in c.get_book_shelves():
        shelves.append(shelf_template % {
            'shelf_name_enc': html.quote(shelf),
            'shelf_name': shelf
            })
    
    body = shelves_template % {
        'label_shelves': _("All Shelves"),
        'shelves': "\n".join(shelves)
        }
    
    return body, [], _("Book shelves")
    
renderers = {'shelf': render_shelf_page}

context_handlers = {}    
